import {onUnmounted, ref} from 'vue';

export default function useWebSocket(url) {
    const messagesData = ref([]);
    const onlineUsersData = ref([])
    // 创建WebSocket连接和相关方法
    const socket = new WebSocket(url);
    socket.onopen = () => {
        console.log('WebSocket连接已建立');
    };

    socket.onmessage = (event) => {
        try {
            const receivedMessage = JSON.parse(event.data);

            // 根据消息类型处理
            if (receivedMessage.type === 'user_join') {
                console.log(`${receivedMessage.username} 已加入`);
                // 更新在线用户列表
                updateOnlineUsers(receivedMessage.online_users);
            } else if (receivedMessage.type === 'user_leave') {
                console.log(`${receivedMessage.username} 已离开`);
                // 更新在线用户列表
                updateOnlineUsers(receivedMessage.online_users);
            } else {
                // 存储接收到的消息及发送者的头像
                messagesData.value.push({
                    message: receivedMessage.message,
                    username: receivedMessage.username,
                    avatar: receivedMessage.avatar // 存储发送者的头像
                });
                console.log(messagesData.value);
            }
        } catch (error) {
            console.error('Error parsing message:', error);
        }
    };
    socket.onerror = (error) => {
        console.error('WebSocket error:', error);
    };
    socket.onclose = () => {
        console.log('WebSocket连接已关闭');
    };
    onUnmounted(() => {
        socket.close();
    });

    function updateOnlineUsers(onlineUsers) {
        // 更新在线用户逻辑，例如存储在线用户的 ref
        onlineUsersData.value = onlineUsers;
    }
    return {
        onlineUsersData,
        messagesData,
        sendMessage: (message) => {
            if (socket.readyState === WebSocket.OPEN) {
                socket.send(message);
            } else {
                console.warn('WebSocket is not open. Cannot send message.');
            }
        },
        closeConnection: () => {
            socket.close();
        }
    };
}